package com.atlige.gzmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atlige.common.constant.CartConstant;
import com.atlige.common.constant.OrderConstant;
import com.atlige.common.exception.NoStockException;
import com.atlige.common.to.mq.OrderTo;
import com.atlige.common.utils.R;
import com.atlige.common.vo.MemberRespVo;
import com.atlige.gzmall.order.entity.OrderItemEntity;
import com.atlige.gzmall.order.entity.OrderReturnReasonEntity;
import com.atlige.gzmall.order.entity.PaymentInfoEntity;
import com.atlige.gzmall.order.feign.CartFeignService;
import com.atlige.gzmall.order.feign.MemberFeignService;
import com.atlige.gzmall.order.feign.ProductFeignService;
import com.atlige.gzmall.order.feign.WmsFeignService;
import com.atlige.gzmall.order.interceptor.LoginUserInterceptor;
import com.atlige.gzmall.order.service.OrderItemService;
import com.atlige.gzmall.order.service.PaymentInfoService;
import com.atlige.gzmall.order.to.OrderCreateTo;
import com.atlige.gzmall.order.vo.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atlige.common.utils.PageUtils;
import com.atlige.common.utils.Query;

import com.atlige.gzmall.order.dao.OrderDao;
import com.atlige.gzmall.order.entity.OrderEntity;
import com.atlige.gzmall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

//@RabbitListener(queues = {"hello.java.queue"})
@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    CartFeignService cartFeignService;
    @Autowired
    WmsFeignService wmsFeignService;
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    OrderItemService orderItemService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {
            // 防止异步编排时上下文丢失问题
            // 每个线程都共享之前的数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            Long memberId = memberRespVo.getId();
            // 1、查询所有的收获地址列表
            // feign在远程调用之前，会调用很多拦截器
            // RequestInterceptor interceptor : requestInterceptors
            confirmVo.setAddressVo(memberFeignService.getAddress(memberId));
        });
        CompletableFuture<Void> cartTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 2、远程查询购物车所有选中的购物项
            confirmVo.setItems(cartFeignService.getCurrentUserCartItems());
        }).thenRunAsync(() -> {
            // 查询库存结果
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> hasStockData = hasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (hasStockData != null) {
                Map<Long, Boolean> map = hasStockData.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        });
        // 3、用户积分信息
        confirmVo.setIntegration(memberRespVo.getIntegration());
        log.info("{}", confirmVo.getItems());
        // 其他数据自动计算
        // TODO 防止重复提交令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressTask, cartTask).get();
        return confirmVo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        confirmVoThreadLocal.set(orderSubmitVo);
        // 1、验证令牌【令牌对比和删除必须原子性】
        // 0 ：验证成功，1：验证失败
        String script = "if redis.call('get',KEYS[1])==ARGV[1]\n" +
                "then return redis.call('del',KEYS[1])\n" +
                "else return 0\n" +
                "end";

        String orderToken = orderSubmitVo.getOrderToken();
        // 原子验证令牌和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if (result == 0L) {
            // 令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            // 验证成功
            // 下单：去创建订单，验证令牌，验价格，锁库存
            // 1、创建订单
            OrderCreateTo order = createOrder();
            // 2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = orderSubmitVo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 金额对比
                // 3、保存订单
                saveOrder(order);
                // 4、锁库存。只要有异常就回滚数据
                // 订单号、所有订单项(skuId, skuName, num)
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                // TODO 远程锁库存
                // 库存成功，由于网络超时，订单回滚，库存不滚
                R res = wmsFeignService.orderLockStock(lockVo);
                if (res.getCode() == 0) {
                    // 锁定成功
                    responseVo.setOrder(order.getOrder());
                    responseVo.setCode(0);
//                    int i = 10 / 0; // 出异常，订单回滚，远程异常不回滚
                    // TODO 订单创建成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return responseVo;
                } else {
                    // 锁失败
                    responseVo.setCode(3);
                    String msg = (String) res.get("msg");
                    throw new NoStockException(msg);
//                    return responseVo;
                }


            } else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    /**
     * 关闭订单
     *
     * @param orderEntity
     */
    @Override
    public void closerOrder(OrderEntity orderEntity) {
        // 查询当前订单最新状态
        OrderEntity byId = getById(orderEntity.getId());
        if (CartConstant.OrderStatusEnum.CREATE_NEW.getCode().equals(byId.getStatus())) {
            // 关单
            OrderEntity entity = new OrderEntity().setStatus(CartConstant.OrderStatusEnum.CANCLED.getCode()).setId(byId.getId());
            updateById(entity);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try {
                // 发给MQ
                // TODO 保证消息一定可以发送出去，每个消息都可以做好日志记录(给数据库保存每个消息的详细信息)
                // TODO 定期扫描数据库将失败的消息再重新发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            }catch (Exception e){
                // TODO 将没发送成功的消息进行重试发送
            }

        }
    }

    /**
     * 1、将支付页让浏览器展示
     * 2、支付成功以后要跳到用户订单列表页
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = getOrderByOrderSn(orderSn);
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString()); // 支付金额
        payVo.setOut_trade_no(orderSn);
        List<OrderItemEntity> orderItemList = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = orderItemList.get(0);
        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(list);
            return order;
        }).collect(Collectors.toList());
        return new PageUtils(page.setRecords(collect));
    }

    /**
     * 处理支付宝的支付结果
     * @param vo
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        // 2、修改订单的状态信息
        if (vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")) {
            // 支付成功
            String outTradeNo = vo.getOut_trade_no();
            baseMapper.updateOrderStatus(outTradeNo, CartConstant.OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        // 1、生成订单号
        String orderSn = IdWorker.getTimeId();
        // 创建订单
        OrderEntity orderEntity = buildOrder(orderSn);
        // 2、获取所有订单项信息
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        // 3、计算价格相关
        computePrice(orderEntity, itemEntities);
        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);
        return createTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        BigDecimal giftGrowth = new BigDecimal("0");
        BigDecimal giftIntegration = new BigDecimal("0");

        for (OrderItemEntity itemEntity : itemEntities) {
            total = total.add(itemEntity.getRealAmount());
            integration = integration.add(itemEntity.getIntegrationAmount());
            coupon = coupon.add(itemEntity.getCouponAmount());
            promotion = promotion.add(itemEntity.getPromotionAmount());
            giftGrowth = giftGrowth.add(new BigDecimal(itemEntity.getGiftGrowth().toString()));
            giftIntegration = giftIntegration.add(new BigDecimal(itemEntity.getGiftIntegration().toString()));
        }
        // 1、订单价格相关
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        // 设置积分信息
        orderEntity.setIntegration(giftIntegration.intValue());
        orderEntity.setGrowth(giftGrowth.intValue());
        orderEntity.setDeleteStatus(0); // 未删除
    }

    /**
     * 创建订单
     *
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        // 创建订单号
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        // 获取收货地址信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        // 设置运费
        orderEntity.setFreightAmount(fareResp.getFare());
        // 设置收货信息
        orderEntity.setReceiverCity(fareResp.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        // 收货人名字
        orderEntity.setReceiverName(fareResp.getAddress().getName());
        orderEntity.setReceiverPhone(fareResp.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        orderEntity.setReceiverRegion(fareResp.getAddress().getRegion());
        // 设置订单的相关状态信息
        orderEntity.setStatus(CartConstant.OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setConfirmStatus(7);
        return orderEntity;
    }

    /**
     * 创建所有订单项
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定每一个购物项价格
        List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
        List<OrderItemEntity> itemEntities = null;
        if (cartItems != null && cartItems.size() > 0) {
            itemEntities = cartItems.stream().map(item -> {
                OrderItemEntity itemEntity = buildOrderItem(item);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    /**
     * 构建某个订单项
     *
     * @param item
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity entity = new OrderItemEntity();
        // 1、订单信息：订单号

        // 2、商品的spu信息
        R spuBySkuId = productFeignService.getSpuBySkuId(item.getSkuId());
        SpuInfoVo spuInfoVo = spuBySkuId.getData(new TypeReference<SpuInfoVo>() {
        });
        entity.setSpuId(spuInfoVo.getId());
        entity.setSpuName(spuInfoVo.getSpuName());
        entity.setSpuBrand(spuInfoVo.getBrandId().toString());
        entity.setCategoryId(spuInfoVo.getCatalogId());
        // 3、商品的sku信息
        entity.setSkuId(item.getSkuId());
        entity.setSkuName(item.getTitle());
        entity.setSkuPic(item.getImage());
        entity.setSkuPrice(item.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
        entity.setSkuAttrsVals(skuAttr);
        entity.setSkuQuantity(item.getCount());
        // 4、优惠信息
        // 5、积分信息
        entity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        entity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        // 6、订单项的价格信息
        entity.setPromotionAmount(new BigDecimal("0"));
        entity.setCouponAmount(new BigDecimal("0"));
        entity.setIntegrationAmount(new BigDecimal("0"));
        // 当前订单项的实际金额
        // 总额
        BigDecimal origin = entity.getSkuPrice().multiply(new BigDecimal(entity.getSkuQuantity().toString()));
        // 优惠后
        BigDecimal subtract = origin.subtract(entity.getCouponAmount()).subtract(entity.getPromotionAmount()).subtract(entity.getIntegrationAmount());
        entity.setRealAmount(subtract);
        return entity;
    }

    /**
     * queues: 声明需要监听的所有队列
     * org.springframework.amqp.core Message
     * Queue: 可以很多人监听。只要收到消息，队列删除消息，而且只能有一个收到消息
     * 场景：
     * 1）订单服务启动多个；同一个消息，只能有一个客户端收到
     * 2）只有一个消息完全处理完，方法运行结束，我们就可以接收到下一个消息
     *
     * @param message 原生消息详细信息。头+体
     * @param content T<发送的消息的类型> OrderEntity content
     * @param channel 当前传输数据的通道
     */
//    @RabbitListener(queues = {"hello.java.queue"})
    //@RabbitHandler
    public void receiveMessage(Message message, OrderEntity content, Channel channel) {
        byte[] body = message.getBody();
        System.out.println("接收到消息：" + content);
        // 消息头属性
        MessageProperties properties = message.getMessageProperties();
        System.out.println("消息处理完成：" + content.getReceiverName());
        // channel内按顺序自增的
        long deliveryTag = properties.getDeliveryTag();
        System.out.println("deliveryTag ->" + deliveryTag);
        // 签收消息,非批量模式
        try {
            if (deliveryTag % 2 == 0) {
                // 收货
                channel.basicAck(deliveryTag, false);
                System.out.println("签收了消息：" + deliveryTag);
            } else {
                // 退货
                // long deliveryTag, boolean multiple, boolean requeue
                // requeue : false 丢弃， true 重新入队
                channel.basicNack(deliveryTag, false, true);
                // long deliveryTag, boolean requeue
                // channel.basicReject();
                System.out.println("没有签收消息：" + deliveryTag);
            }

        } catch (IOException e) {
            // 网络异常
        }
    }

    // @RabbitHandler
    public void receiveMessage(OrderReturnReasonEntity content) {
        System.out.println("接收到消息：" + content);
    }

}
